package com.iotproject.studyservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.iotproject.servicebase.exceptionhandler.GlobalException;
import com.iotproject.studyservice.entity.StudyReading;
import com.iotproject.studyservice.entity.excel.StudyReadingData;
import com.iotproject.studyservice.service.StudyReadingService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class StudyReadingExcelListener extends AnalysisEventListener<StudyReadingData> {

    StudyReadingService studyReadingService;

    public StudyReadingExcelListener() {
    }

    public StudyReadingExcelListener(StudyReadingService studyReadingService) {
        this.studyReadingService = studyReadingService;
    }

    @Override
    public void invoke(StudyReadingData studyReadingData, AnalysisContext analysisContext) {
        if (studyReadingData == null) {
            throw new GlobalException(20001, "文件数据为空");
        }
        String name = studyReadingData.getName();
        String author = studyReadingData.getAuthor();
        String description = studyReadingData.getDescription();
        String content = studyReadingData.getContent();
        String cover = studyReadingData.getCover();

        StudyReading book = exitBook(studyReadingService, name);
        if (book == null) {
            book = new StudyReading();
            book.setName(name);
            book.setAuthor(author);
            book.setDescription(description);
            book.setContent(content);
            book.setCover(cover);
            studyReadingService.save(book);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    public StudyReading exitBook(StudyReadingService studyReadingService, String name) {
        QueryWrapper<StudyReading> studyReadingQueryWrapper = new QueryWrapper<>();
        studyReadingQueryWrapper.eq("name", name);
        StudyReading book = studyReadingService.getOne(studyReadingQueryWrapper);
        return book;
    }

}
